package org.assocsp3.web;

import org.assocsp3.modele.Personne;
import org.assocsp3.service.PersonneService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import org.springframework.dao.DataIntegrityViolationException;

@Controller
@RequestMapping("/register")
public class RegisterController {

	private Logger logger = org.slf4j.LoggerFactory.getLogger(RegisterController.class);

	private PersonneService personneServ;
	
	@Autowired
    public void setPersonneServ(PersonneService personneServ) {
        this.personneServ = personneServ;
    }
	
	@SuppressWarnings("deprecation")
	@RequestMapping(method = RequestMethod.GET)
	public ModelMap initPersonne() {
		logger.info("Register");
		ModelMap mm = new ModelMap();
		mm.addObject("personne", new Personne());
		return mm;  
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping(method=RequestMethod.POST)
	public String processForm(@Valid Personne personne, BindingResult result, ModelMap model)
	{
		if(!result.hasErrors()&&personne.memeMdp())
		{
			try {
				personne.setActif(false);
				personne.setRole("ROLE_ADHE");
				this.personneServ.ajouter(personne);
				model.addObject("regSuc", "Vous etes maintenant inscrit!" +
						" <a href=\"#\">Activez votre compte</a>");
			}
			catch (DataIntegrityViolationException d) {
				personne.setLogin("");
				model.clear();
				model.addObject("personne", personne);
				model.addObject("loginExt", "Login deja utilise");
			}			
		}
		else
			model.addObject("mdpErr", "confirmation du mot de passe invalide");
		return "register";
	}
}
